package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings("all")
public class AliPayServiceImpl implements AlipayService {

    @Autowired
    private OrderFeignClient orderFeignClient;


    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AlipayClient alipayClient;
    /**
     * 支付宝预下单
     * @param orderId
     * @return
     */
    @Override
    public String createAlipay(Long orderId) {

        //获取订单信息
       Result<OrderInfo> result= orderFeignClient.getOrderInfo(orderId);
        String string = JSONObject.toJSONString(result.getData());
        OrderInfo orderInfo = JSONObject.parseObject(string, OrderInfo.class);

        //判断订单的状态
        if (orderInfo == null || !"UNPAID".equals(orderInfo.getOrderStatus()) || !"UNPAID".equals(orderInfo.getProcessStatus())) {


            return "当前订单异常，请返回查看，再支付。。";
        }

        //记录支付信息
        paymentService.savePayment(orderInfo, PaymentType.ALIPAY.name());

        //对接支付宝
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
                request.setNotifyUrl(AlipayConfig.notify_payment_url);
        //同步跳转地址，仅支持http/https
                request.setReturnUrl(AlipayConfig.return_payment_url);
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", 0.01);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", orderInfo.getTradeBody());
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //设置相对有效时间
        bizContent.put("timeout_express", "11m");


        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();

        }
        return response.getBody();
    }

    /**
     * 退款
     * @param orderId
     */
    @Override
    public Result refund(Long orderId) {

        //查询交易订单号
        //获取订单信息
        Result<OrderInfo> result= orderFeignClient.getOrderInfo(orderId);
        String string = JSONObject.toJSONString(result.getData());
        OrderInfo orderInfo = JSONObject.parseObject(string, OrderInfo.class);

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("refund_amount", 0.01);


        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getFundChange());
            //判断
            if("Y".equals(response.getFundChange())){

                return Result.ok("退款成功");
            }else{

                return Result.ok("退款失败");
            }


        } else {
            System.out.println("调用失败");

        }

         return result.fail("退款失败");


    }

    /**
     * 查询退款结果
     * @param orderId
     * @return
     */
    @Override
    public Result findRefund(Long orderId) {
        //获取订单信息
        Result<OrderInfo> result= orderFeignClient.getOrderInfo(orderId);
        String string = JSONObject.toJSONString(result.getData());
        OrderInfo orderInfo = JSONObject.parseObject(string, OrderInfo.class);

        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("out_request_no", orderInfo.getOutTradeNo());


        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getRefundStatus());
            if("REFUND_SUCCESS".equals(response.getRefundStatus())){

                return result.ok("退款已到账，请查看你的账户。。。。");
            }

        } else {


            System.out.println("调用失败");
        }
        return result.fail("退款失败，请联系客服，电话：17610026026.。。");
    }

    /**
     * 查询支付宝交易记录
     * @param orderId
     * @return
     */
    @Override
    public boolean checkPayment(Long orderId) {

        //查询
        Result<OrderInfo> result= orderFeignClient.getOrderInfo(orderId);
        String string = JSONObject.toJSONString(result.getData());
        OrderInfo orderInfo = JSONObject.parseObject(string, OrderInfo.class);

        //判断
        if(orderInfo==null) return false;



        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        if(response.isSuccess()){
            System.out.println("调用成功");
            if("WAIT_BUYER_PAY".equals(response.getTradeStatus())){

                return true;
            }


        }
        return false;
    }


    /**
     * 关闭支付宝记录
     * @param orderId
     * @return
     */
    @Override
    public boolean closePay(Long orderId) {

        //查询
        Result<OrderInfo> result= orderFeignClient.getOrderInfo(orderId);
        String string = JSONObject.toJSONString(result.getData());
        OrderInfo orderInfo = JSONObject.parseObject(string, OrderInfo.class);

        //判断
        if(orderInfo==null) return false;

        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");

            return false;
        }

    }
}
